package dom;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Personne
{

  public static void main(String[] args)
  {

    try
    {
      final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      final DocumentBuilder builder = factory.newDocumentBuilder();
      final Document document = builder.parse(new File("src/test.xml"));
//      System.out.println(document.getXmlVersion());
//      System.out.println(document.getXmlStandalone());
      final Element racine = document.getDocumentElement();
//      System.out.println(racine.getNodeName());
      final NodeList racineNoeuds = racine.getChildNodes();
//      System.out.println(nbRacineNoeuds);
//      for (int i = 0; i < nbRacineNoeuds; i++)
//      {
//        System.out.println(racineNoeuds.item(i).getNodeName());
//      }

      System.out.println("##########");
      
      for (int i = 0; i<racineNoeuds.getLength(); i++) {
        if(racineNoeuds.item(i).getNodeType() == Node.ELEMENT_NODE) {
            final Element  personne = (Element )racineNoeuds.item(i);
            System.out.println(personne.getNodeName());
            System.out.println("sexe : " + personne.getAttribute("sexe"));
            final Element nom = (Element) personne.getElementsByTagName("nom").item(0);
            final NodeList telephones=personne.getElementsByTagName("telephones");
            System.out.println("Nom : " + nom.getTextContent());
            System.out.println(telephones.getLength());
            for (int j=0; j<telephones.getLength();j++){
              final Element telephone=(Element)telephones.item(j);
              System.out.println(telephone.getAttribute("type") + " : " + telephone.getTextContent());
            }           
        }               
      }
      
    }
    catch (ParserConfigurationException e)
    {
      e.printStackTrace();
    }
    catch (SAXException e)
    {
      e.printStackTrace();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

}
